using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Debug = System.Diagnostics.Debug;

public class HealthBar : MonoBehaviour
{
    public GameObject followTarget;
    [SerializeField]
    private float yOffset = 100f; // 可调整的Y轴偏移量（屏幕像素）
    [SerializeField]
    private float buffTime = 0.5f;//白色和红色重叠的缓冲时间

    private GameObject _bar;
    private GameObject _effect;
    private Text _barText;
    private Coroutine _bufferCoroutine; // 保存协程引用，用于取消

    private void Awake()
    {
        _bar = transform.Find("Bar").gameObject;
        _barText = transform.Find("hp").GetComponent<Text>();
        _effect = transform.Find("Effect").gameObject;
        
        // 确保初始状态两个血条一致
        if (_effect != null && _bar != null)
        {
            _effect.GetComponent<Image>().fillAmount = _bar.GetComponent<Image>().fillAmount;
        }
    }

    private void LateUpdate()
    {
        SetPosition();
        //UpdateHp();
    }
    /// <summary>
    /// 设置位置
    /// </summary>
    private void SetPosition()
    {
        if (followTarget == null || Camera.main == null) return;
        
        //将followTarget的位置转换为屏幕坐标
        Vector3 screenPos = Camera.main.WorldToScreenPoint(followTarget.transform.position);
        
        // 在屏幕坐标系中向上偏移
        screenPos.y += yOffset; // 在Y轴上增加偏移量
        
        transform.position = screenPos;
    }
    /// <summary>
    /// 更新血量
    /// </summary>
    public void UpdateHp(float hp, float currenHp)
    {
        // 保存当前白色血条的填充量
        float previousFillAmount = _effect.GetComponent<Image>().fillAmount;
        
        // 更新红色血条
        _bar.GetComponent<Image>().fillAmount = hp;
        _barText.text = currenHp.ToString();
        
        // 如果hp小于之前的效果值，才需要缓冲效果
        if (hp < previousFillAmount)
        {
            // 取消已有的协程（如果存在）
            if (_bufferCoroutine != null)
            {
                StopCoroutine(_bufferCoroutine);
            }
            
            // 启动新的缓冲效果
            _bufferCoroutine = StartCoroutine(UpdateEffect());
        }
        else
        {
            // 如果血量增加，直接将白色血条与红色血条同步
            _effect.GetComponent<Image>().fillAmount = hp;
            
            // 确保取消已有协程
            if (_bufferCoroutine != null)
            {
                StopCoroutine(_bufferCoroutine);
                _bufferCoroutine = null;
            }
        }
    }

    /// <summary>
    /// 更新白色血条缓冲效果
    /// </summary>
    /// <returns></returns>
    private IEnumerator UpdateEffect()
    {
        float startFillAmount = _effect.GetComponent<Image>().fillAmount;
        float targetFillAmount = _bar.GetComponent<Image>().fillAmount;
        float elapsedTime = 0;
        
        while(elapsedTime < buffTime && startFillAmount > targetFillAmount)
        {
            elapsedTime += Time.deltaTime;
            // 从起始值到目标值随时间插值
            _effect.GetComponent<Image>().fillAmount = Mathf.Lerp(startFillAmount, targetFillAmount, elapsedTime / buffTime);
            yield return null;
        }
        
        // 确保最终值正确
        _effect.GetComponent<Image>().fillAmount = targetFillAmount;
        _bufferCoroutine = null;
    }

    // 当血条被销毁时（例如敌人死亡），确保停止所有协程
    private void OnDestroy()
    {
        if (_bufferCoroutine != null)
        {
            StopCoroutine(_bufferCoroutine);
        }
    }
}
